//package com.lanhao.aot.carrierintegration.rupost.bak;
//
//import java.awt.Color;
//import java.awt.Font;
//import java.awt.Graphics2D;
//import java.awt.Image;
//import java.awt.Rectangle;
//import java.awt.RenderingHints;
//import java.awt.image.BufferedImage;
//import java.io.ByteArrayInputStream;
//import java.io.ByteArrayOutputStream;
//import java.io.File;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.net.URL;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//
//import javax.imageio.ImageIO;
//import javax.imageio.stream.ImageOutputStream;
//
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.lang3.ArrayUtils;
//import org.apache.commons.lang3.StringUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONArray;
//import com.alibaba.fastjson.JSONObject;
//import com.alibaba.fastjson.JSONValidator;
//import com.alibaba.fastjson.JSONValidator.Type;
//import com.google.common.collect.Maps;
//import com.google.zxing.BarcodeFormat;
//import com.google.zxing.EncodeHintType;
//import com.google.zxing.client.j2se.MatrixToImageWriter;
//import com.google.zxing.oned.Code128Writer;
//import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
//import com.oxygen.common.constant.BizConstants;
//import com.oxygen.insure.common.util.PDF2ImageUtil;
//
//import cn.hutool.core.codec.Base64;
//import cn.hutool.core.img.ImgUtil;
//import cn.hutool.core.lang.UUID;
//import cn.hutool.core.util.StrUtil;
//import cn.hutool.http.HttpRequest;
//
//public class RussianPostUtil {
//	private static final Logger LOG = LoggerFactory.getLogger(RussianPostUtil.class);
//	public static final String RETURN_ORDER_URL = "https://otpravka-api.pochta.ru/1.0/returns/return-without-direct";
//	public static final String CLEAN_ADDRESS_URL = "https://otpravka-api.pochta.ru/1.0/clean/address";
//	public static final String RETURN_PDF_URL = "https://otpravka-api.pochta.ru/1.0/forms/{}/easy-return-pdf";
//	public static final String TOKEN = "O_Gcx3x0RskhZ71aQd304IjCmxmF2EZk";
//	public static final String LOGIN = "fominih91@mail.ru";
//	public static final String PASSWORD = "1851204";
//	public static final Boolean useDiyImage = true;
//	public static String AUTHORIZATION = Base64.encode(LOGIN + ":" + PASSWORD);
//	public static final String[] goodQualityCodes = {"GOOD", "POSTAL_BOX", "ON_DEMAND", "UNDEF_05"};
//	public static final String[] goodValidationCodes = {"VALIDATED", "OVERRIDDEN", "CONFIRMED_MANUALLY"};
//	
//	public static void main(String[] args) {
////		doReturnOrder();
////		JSONObject address = new JSONObject();
////		address.put("id", "WarehouseAddress");
////		address.put("original-address", "Москва, ул. Снежная 19/2 кв 185");
////		System.out.println(address.toJSONString());
////		getCleanAddress(address.toJSONString());
//		getBarCodePdfFile("80098679467596");
//		
////		doDiyLabel("80107277381019");
//		
//	}
//	
//	public static void doReturnOrder() {
//		JSONArray requestArray = new JSONArray();
//		JSONObject request = new JSONObject();
//		
//		JSONObject addressFrom = new JSONObject();
//		addressFrom.put("address-type", "DEFAULT");
//		
//		String sendAddress = "город Вятские Поляны, улица Кирова,дом 10,квартира 59";
//		JSONArray addressRequestArray = new JSONArray();
//		JSONObject addressRequest = new JSONObject();
//		addressRequest.put("id", "sendAddress");
//		addressRequest.put("original-address", sendAddress);
//		addressRequestArray.add(addressRequest);
//		String cleanAddressResp = getCleanAddress(addressRequestArray.toJSONString());
//		if(StringUtils.isBlank(cleanAddressResp)) {
//			return;
//		}
//		// quality-code必须是：GOOD、POSTAL_BOX、ON_DEMAND 或 UNDEF_05。
//		// validation-code必须是：VALIDATED、OVERRIDDEN 或 CONFIRMED_MANUALLY。
//		JSONArray addressArray = JSON.parseArray(cleanAddressResp);
//		if(addressArray == null || addressArray.size() == 0) {
//			LOG.info("发件人地址转换失败，返回数据为空");
//			return;
//		}
//		JSONObject addressObject = addressArray.getJSONObject(0);
//		String qualityCode = addressObject.getString("quality-code");
//		String validationCode = addressObject.getString("validation-code");
//		if(!ArrayUtils.contains(goodQualityCodes, qualityCode) || !ArrayUtils.contains(goodValidationCodes, validationCode)) {
//			LOG.info("发件人地址转换失败，地址不规范");
//			return;
//		}
//		addressFrom.put("index", addressObject.getString("index")); // 根据地址转换接口返回，必填
//		addressFrom.put("place", addressObject.getString("place")); // 根据地址转换接口返回，必填
//		addressFrom.put("region", addressObject.getString("region")); // 根据地址转换接口返回，必填
//		addressFrom.put("house", addressObject.getString("house")); // 根据地址转换接口返回
//		addressFrom.put("location", addressObject.getString("location")); // 根据地址转换接口返回
//		addressFrom.put("room", addressObject.getString("room")); 	// 根据地址转换接口返回
//		addressFrom.put("street", addressObject.getString("street")); // 根据地址转换接口返回
//		request.put("address-from", addressFrom);
//		
//		request.put("insr-value", 0);
//		request.put("mail-type", "EASY_RETURN"); // 固定值
//		request.put("order-num", UUID.fastUUID().toString(true)); // 内部单号，随便传
//		request.put("postoffice-code", "102961"); // 邮局编码，固定值
//		request.put("recipient-name", "Вэнь жуй"); //收件人
//		request.put("sender-name", "Bronski Beat"); //发件人
//		requestArray.add(request);
//		
//		createReturnOrder(requestArray.toJSONString());
//	}
//	
//	public static Map<String, String> getRequestHeader() {
//		Map<String, String> headers = Maps.newHashMap();
//		headers.put("Content-Type", "application/json");
//		headers.put("Accept", "application/json;charset=UTF-8");
//		headers.put("Authorization", "AccessToken " + TOKEN);
//		headers.put("X-User-Authorization", "Basic " + AUTHORIZATION);
//		return headers;
//	}
//	
//	
//	public static String createReturnOrder(String requestBody) {
//		Map<String, String> headers = getRequestHeader();
//		String respBody = HttpRequest.put(RETURN_ORDER_URL).addHeaders(headers).body(requestBody).execute().body();
//		LOG.info("url={}, header={}, request={}, response={}", RETURN_ORDER_URL, headers, requestBody, respBody);
//		Type type = JSONValidator.from(respBody).getType();
//		if(Type.Object.equals(type)) {
//			JSONObject orderCreateRespObject = JSON.parseObject(respBody);
//			String code = orderCreateRespObject.getString("code");
//			String subCode = orderCreateRespObject.getString("sub-code");
//			LOG.info("请求失败，code=" + code + "|subCode=" + subCode);
//			return "";
//		}
//		JSONArray orderCreateRespArray = JSON.parseArray(respBody);
//		if (orderCreateRespArray != null && orderCreateRespArray.size() > 0) {
//			JSONObject orderCreateRespObject = orderCreateRespArray.getJSONObject(0);
//			JSONArray errorArray = orderCreateRespObject.getJSONArray("errors");
//			if(errorArray != null && errorArray.size() > 0) {
//				JSONObject errorObject = errorArray.getJSONObject(0);
//				String code = errorObject.getString("code");
//				String description = errorObject.getString("description");
//				LOG.info("请求失败，code=" + code + "|description=" + description);
//				return "";
//			}
//			String barCode = orderCreateRespObject.getString("return-barcode");
//			LOG.info("请求成功，barCode=" + barCode);
//			LOG.info("俄罗斯邮政保存面单信息至本地开始...");
//			// 申请生成面单 -- 此处做异步处理，先返回固定的地址
//			if(useDiyImage) {
//				doDiyLabel(barCode);
//			} else {
//				getBarCodePdfFile(barCode);
//			}
//			LOG.info("俄罗斯邮政保存面单信息至本地结束...");
//			return barCode;
//		}
//		
//		return "";
//	}
//	
//	public static String getCleanAddress(String requestBody) {
//		Map<String, String> headers = getRequestHeader();
//		String respBody = HttpRequest.post(CLEAN_ADDRESS_URL).addHeaders(headers).body(requestBody).execute().body();
//		LOG.info("url={}, header={}, request={}, response={}", CLEAN_ADDRESS_URL, headers, requestBody, respBody);
//		return respBody;
//	} 
//	
//	public static void getBarCodePdfFile(String barCode) {
//		Map<String, String> headers = getRequestHeader();
//		String pdfUrl = StrUtil.format(RETURN_PDF_URL, barCode) + "?print_type=PAPER";
//		File localDestFile = new File("D:/RussianPost_" + barCode + ".pdf");
//		long respBody = HttpRequest.get(pdfUrl).addHeaders(headers).execute().writeBody(localDestFile);
//		LOG.info("url={}, header={}, response={}", pdfUrl, headers, respBody);
//		String imageFinalLabelName = BizConstants.Carrier.RUSSIAN_POST + "_" + barCode + "." + BizConstants.DEFAULT_LABEL_IMAGE_TYPE;
//		String imageCutLabelName = BizConstants.Carrier.RUSSIAN_POST + "_" + barCode + "_CUT." + BizConstants.DEFAULT_LABEL_IMAGE_TYPE;
//		try {
//			BufferedImage image = PDF2ImageUtil.pdf2Image(localDestFile, null);
//			File cutFile = new File("D:/" + imageCutLabelName);
//			ImgUtil.cut(image, cutFile, new Rectangle(0, 0, 1180, 835));
//			List<BufferedImage> imageList = new ArrayList<BufferedImage>();
//			imageList.add(ImageIO.read(cutFile));
//			imageList.add(PDF2ImageUtil.ruTemplateImage);
//			PDF2ImageUtil.mergeImagetogeter(new File("D:/" + imageFinalLabelName), imageList, "PNG", "0");
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}
//	
//	public static void doDiyLabel(String barCode) {
//		String imageFinalLabelName = BizConstants.Carrier.RUSSIAN_POST + "_" + barCode + "." + BizConstants.DEFAULT_LABEL_IMAGE_TYPE;
//		InputStream inputStream = null;
//		OutputStream outStream = null;
//		ByteArrayOutputStream bs = null;
//		ImageOutputStream imOut = null;
//		try {
//			BufferedImage image = ImageIO.read(new URL("https://res-oss.anhelogistics.com/image/RussianPostDiyTemplateWithLogo.png"));
//			Graphics2D gd = image.createGraphics();
//			gd.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//
//			HashMap<EncodeHintType, Object> m = new HashMap<>();// 条形码的参数
//			m.put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码
//			m.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 条形码的容错率,从小到大是L,M,Q,H,条形码的容错率越高越容易扫描
//			m.put(EncodeHintType.MARGIN, 0);// 条形码的边框宽度
//			Image i = MatrixToImageWriter.toBufferedImage(new Code128Writer().encode(barCode, BarcodeFormat.CODE_128, 300, 50, m));// 生成条形码的图片
//			gd.drawImage(i, 160, 35, null);
//
//			gd.setColor(Color.BLACK);
//			gd.setFont(new Font("黑体", Font.BOLD, 18));
//			gd.drawString(barCode, 240, 105);
//			gd.dispose();
//
//			bs = new ByteArrayOutputStream();
//			imOut = ImageIO.createImageOutputStream(bs);
//			ImageIO.write(image, "PNG", imOut);
//			inputStream = new ByteArrayInputStream(bs.toByteArray());
//			outStream = new FileOutputStream(new File("D:/" + imageFinalLabelName));
//			IOUtils.copy(inputStream, outStream);
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			try {
//				if (inputStream != null) {
//					inputStream.close();
//				}
//				if (inputStream != null) {
//					outStream.close();
//				}
//				if (bs != null) {
//					bs.close();
//				}
//				if (imOut != null) {
//					imOut.close();
//				}
//			} catch (Exception x) {
//				x.printStackTrace();
//			}
//		}
//	}
//}
